<?php

declare(strict_types=1);

namespace app\common\model;

use addons\Target\facade\Target;
use addons\V2\admin\model\Order;
use think\facade\Cache;
use think\facade\Event;
use app\common\controller\Config;

class UserRelease extends Base
{
    protected $name = 'user_release';

    public function user()
    {
        return $this->hasOne(User::class, 'id', 'uid')->field('id,code,is_active,level_id,nickname,mobile,parent_id');
    }

    public function cate()
    {
        return $this->hasOne(TakeCate::class, 'id', 'cate_id')->field('id,title');
    }

    public function getCappingTimeAttr($value)
    {
        return $value ? date('Y-m-d H:i:s', $value) : '';
    }

    public function getStatusAttr($value)
    {
        return $value == 1 ? '释放中' : '已封顶';
    }


    public static function add($param, $user): array
    {
        parent::startTrans();
        try {
            $cate = TakeCate::where('id', $param['cate_id'])->find();
            if (empty($cate)) {
                return ['code' => -1, 'msg' => '面值错误'];
            }
            $total = $cate->amount * $param['num'];
            if ($user->assets->currency < $total) {
                return ['code' => -1, 'msg' => '余额不足'];
            }
            $count = parent::where('uid', $user->id)->count();
            if ($count) {
                if ($count - 1 >= $user->consume_2) {
                    return ['code' => -1, 'msg' => '您需要在大众区消费过后才能购买提货券'];
                }
            }
            //获取加速比例
            $speed = Speed::where('id', '<=', $param['num'])->order('id', 'desc')->find();

            UserRelease::create([
                'uid'        => $user->id,
                'cate_id'    => $cate->id,
                'cate_title' => $cate->title,
                'amount'     => $total,
                'capping'    => $cate->give * $param['num'],
                'surplus'    => $cate->give * $param['num'],
                'num'        => $param['num'],
                'tp'         => round($cate->tp + $cate->tp * $speed->tp, 4)
            ]);
            Target::Account()->basics($user->id, 'currency', $total, '购买提货券', '-')
                ->createNormal();
            Target::Account()->basics($user->id, 'take', $total, '购买提货券', '+')
                ->createNormal();
            if ($user->is_active != 2) {
                $user->is_active = 2;
                $user->active_time = time();

                $user->is_gw = 1;
                $user->is_transfer = 1;

                Relation::update(['status' => 1], ['new_uid' => $user->id]);
            }
            $user->take_my_total += $total;
            $user->save();

            Relation::renewTeamTotal($total, $user->id, 'take_team_total');

            parent::commit();
            return ['code' => 1, 'msg' => '请您尽快提货，感谢支持'];
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    /**
     * @return array
     * 原点 2022年9月15日15:00:57 释放
     */
    public static function release(): array
    {

        $sysm = Config::lists();
        parent::startTrans();
        try {
            $list = parent::where('status', 1)->select();
            $expendTotal = 0;
            //释放静态
            foreach ($list as $v) {
                $user = User::where(['id' => $v->uid])->find();
                $amount = round(($v->capping * $user['lotto']), 2);
                $diff = $v->capping;
                if ($diff <= $amount) {
                    $amount = $diff;
                    $v->status = 2;
                    $v->capping_time = time();
                    $user->is_out = 1;
                    $user->save();
                }
                $v->day_released = $amount;
                $v->released += $amount;
                $v->save();
                $expendTotal += $amount;
                Target::Account()->basics($v->uid, 'bonus', round(($amount * $sysm['tongzheng']), 2), '静态释放通证积分', '+')
                    ->createBonus($v->uid, 1);
                Target::Account()->basics($v->uid, 'integral', round(($amount * $sysm['jiangli']), 2), '静态释放奖励积分', '+')
                    ->createBonus($v->uid, 1);
                Target::Account()->basics($user['id'], 'green_integral', $amount, '静态奖励释放', '-')
                    ->createNormal();
            }
            if ($expendTotal > 0) {
                Event::trigger('Statistics', ['key' => 'expend', 'value' => $expendTotal]);
            }
            parent::commit();
            return ['code' => 1, 'msg' => 'success'];
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 动态释放
     */
    public static function dynamic_release($money, $jiangli, $user, $uid, $msg, $bl, $num)
    {
        $sysm = Config::lists();
        parent::startTrans();
        try {

            $expendTotal = 0;
            if ($user->assets->green_integral > 0) {

                $list = parent::where(['status' => 1, 'uid' => $user->id])->find();
                //动态释放
                $tp = $jiangli * $bl;
                $amount = round(($money * $tp), 2);
                //return $amount;
                //print_r($tp);die;
                $diff = $user->assets->green_integral;
                if ($diff <= $amount) {
                    $amount = $diff;
                    $list->status = 2;
                    $list->capping_time = time();
                    $user->is_out = 1;
                    $user->save();
                }
                $list->day_released = $amount;
                $list->released += $amount;
                $list->save();
                $expendTotal += $amount;
                if ($amount > 0) {
                    Target::Account()->basics($user->id, 'bonus', round(($amount * $sysm['tongzheng']), 2), $msg, '+')
                        ->createBonus($uid, $num);
                    Target::Account()->basics($user->id, 'integral', round(($amount * $sysm['jiangli']), 2), $msg, '+')
                        ->createBonus($uid, $num);
                    Target::Account()->basics($user['id'], 'green_integral', $amount, $msg, '-')
                        ->createNormal();
                }
                if ($expendTotal > 0) {
                    Event::trigger('Statistics', ['key' => 'expend', 'value' => $expendTotal]);
                }
            }
            parent::commit();
            return ['code' => 1, 'msg' => 'success', 'money' => $expendTotal];
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    public static function testingCapping($uid, $amount)
    {
        $list = parent::where(['uid' => $uid, 'status' => 1])
            ->order('create_time', 'asc')
            ->field('id,capping,released,surplus,status')->select();

        if ($list->isEmpty()) {
            return 0;
        }
        //当前订单封顶
        $new_amount = 0;
        foreach ($list as $vo) {
            if ($amount <= 0) {
                break;
            }
            $diff = $vo->capping - $vo->released;
            if ($diff <= $amount) {
                $vo->released += $diff;
                $vo->surplus -= $diff;
                $vo->status = 2;
                $vo->capping_time = time();
                $vo->save();

                $new_amount += $diff;
                $amount -= $diff;
            } else {
                $vo->released += $amount;
                $vo->surplus -= $amount;
                $vo->save();
                $new_amount += $amount;
                break;
            }
        }

        return $new_amount;
    }
}
